package com.swift.base;

import java.util.ArrayList;
import java.util.List;

import org.json.JSONException;
import org.json.JSONObject;
import org.xutils.HttpManager;
import org.xutils.x;
import org.xutils.common.Callback;
import org.xutils.common.Callback.CommonCallback;
import org.xutils.http.RequestParams;
import org.xutils.http.request.HttpRequest;

import android.util.Log;

import com.google.gson.Gson;
import com.swift.R;
import com.swift.base.ApplicationListener.OnPostExecutedListener;
import com.swift.bean.LoginUser;

public  class WebApiBase {

	public static final int API_SUCCESS_CODE = 0;
	public static final int API_FAILURE_CODE = 1;
	public static final String API_PATH = "/Api/Api";
	public static final String API_LOGIN_URL = "/login";
	public static final String API_CHANGEPASSWORD_URL = "/changePassword";
	public static final String API_ADDSUGGEST_URL = "/addSuggest";
	public static final String API_CODE = "code";
	public static final String API_DATA = "message";
	public static final String API_TOKEN_KEY = "access-token"; 
	
	private String  token;

	public String getToken() {
		return token;
	}

	public void setToken(String token) {
		this.token = token;
	}

	private String remoteHost;
	
	public String getremoteHost() {
		return remoteHost;
	}

	public void setremoteHost(String remoteHost) {
		this.remoteHost = remoteHost;
	}
		
	public WebApiBase(String remoteHost, String token){
		this.token = token;
		this.remoteHost = remoteHost;
	}
	
	public WebApiBase(String remoteHost){
		this(remoteHost, null);
	}

	public WebApiBase(){
		this(null, null);
	}
	
	protected  void postExecuted(OnPostExecutedListener callback, int tag,  Object result){
		if (callback != null){
			callback.postExecuted(tag,  result);
		}
	}
	
	protected  boolean hasJsonData(String json){
		return !(json.equalsIgnoreCase("null") ||  json.equalsIgnoreCase("[]") || json.equalsIgnoreCase("{}"));
	}
	
	protected RequestParams getBaseRequestParams(String action){
		return new RequestParams(remoteHost + API_PATH + action);
	}
	
	protected void asynPost(RequestParams requestParams, final OnPostExecutedListener callback){
		if (!ApplicationBase.checkNetworkAvailable()){
			String errString = ApplicationBase.Context.getResources().getString(R.string.err_http_response);
			this.postExecuted(callback, API_FAILURE_CODE,   errString);
			return;
		}
		
		//add header的时候，一定不能有“_"号
		if (this.getToken() != null){
			requestParams.addHeader(API_TOKEN_KEY,  this.getToken());
		}
		x.http().post(requestParams, new Callback.CommonCallback<String>() {
			@Override
			public void onSuccess(String result) {
				try {
					JSONObject jnb = new JSONObject(result);
					WebApiBase.this.postExecuted(callback, jnb.getInt(API_CODE),  jnb.getString(API_DATA));
				} catch (JSONException e) {
					e.printStackTrace();
					WebApiBase.this.postExecuted(callback, API_FAILURE_CODE,   e.getMessage());
				}
			}

			@Override
			public void onError(Throwable ex, boolean isOnCallback) {
				 String errString = ApplicationBase.Context.getResources().getString(R.string.err_http_response);
				WebApiBase.this.postExecuted(callback, API_FAILURE_CODE,   errString+ ex.getMessage());
			}

			@Override
			public void onCancelled(
					CancelledException paramCancelledException) {
				// TODO Auto-generated method stub
				
			}

			@Override
			public void onFinished() {
				// TODO Auto-generated method stub
				
			}
		});
	}
	
	
	public void login(String account,  String password, final OnPostExecutedListener callback){
		RequestParams params = getBaseRequestParams(API_LOGIN_URL);
		params.addBodyParameter("account",  account);
		params.addBodyParameter("password",  password);
		 asynPost(params,  new OnPostExecutedListener() {						
				@Override
				public void postExecuted(int tag, Object result) {
					if (tag == API_SUCCESS_CODE) {
						try {
							String json = result.toString();
							if (hasJsonData(json)){
								JSONObject jnb = new JSONObject(json);
								setToken(jnb.getString(API_TOKEN_KEY));
								LoginUser user = new Gson().fromJson(jnb.getString("user"), LoginUser.class);
								LoginUser.setInstance(user);
								WebApiBase.this.postExecuted(callback, API_SUCCESS_CODE,  user);
							}														
						} catch (Exception e) {
							e.printStackTrace();
							WebApiBase.this.postExecuted(callback, API_FAILURE_CODE,  e.getMessage());
						}						
					}else{
						WebApiBase.this.postExecuted(callback, API_FAILURE_CODE,  result.toString());
					}
				}
			});
	}
	
	public void changePassword(String password, String newPassword, String access_token,final OnPostExecutedListener callback){
		RequestParams params = getBaseRequestParams(API_CHANGEPASSWORD_URL);
		params.addBodyParameter("access_token",  access_token);
		params.addBodyParameter("old_password",  password);
		params.addBodyParameter("new_password",  newPassword);
		 asynPost(params,  callback);
	}
	
	public void addSuggest(String title, String content, final OnPostExecutedListener callback){
		RequestParams params = getBaseRequestParams(API_ADDSUGGEST_URL);
		params.addBodyParameter("title",  title);
		params.addBodyParameter("content",  content);
		asynPost(params,  callback);
	}
}
